<template>
  <el-dialog
      v-model="visible"
      :title="mode === 'add' ? '新增部门' : '编辑部门'"
      width="600px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        label-position="right"
    >
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="formData.deptName" placeholder="请输入部门名称" />
      </el-form-item>

      <el-form-item label="上级部门" prop="parentId">
        <el-select
            v-model="formData.parentId"
            placeholder="请选择上级部门"
            style="width: 100%"
            clearable
        >
          <el-option label="无上级部门" :value="0" />
          <el-option
              v-for="dept in deptList"
              :key="dept.deptId"
              :label="dept.deptName"
              :value="dept.deptId"
              :disabled="dept.deptId === formData.deptId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="排序" prop="orderNum">
        <el-input-number
            v-model="formData.orderNum"
            :min="0"
            :max="999"
            controls-position="right"
        />
      </el-form-item>

      <el-form-item label="负责人" prop="leader">
        <el-input v-model="formData.leader" placeholder="请输入负责人姓名" />
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio label="0">启用</el-radio>
          <el-radio label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="角色编码只能包含大写字母和下划线handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { saveDept, updateDept, findDept } from '@/api/dept'

const props = defineProps({
  modelValue: Boolean,
  deptData: Object,
  mode: String
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const loading = ref(false)
const formRef = ref()
const deptList = ref([])

const formData = reactive({
  deptName: '',
  parentId: 0,
  orderNum: 0,
  leader: '',
  phone: '',
  email: '',
  status: '0'
})

const rules = {
  deptName: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 30, message: '部门名称长度在2-30个字符', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 获取部门列表
const fetchDeptList = async () => {
  try {
    const response = await findDept({ page: 1, rows: 1000 })
    deptList.value = response.data.list || response.data
  } catch (error) {
    console.error('获取部门列表失败:', error)
  }
}

// 处理对话框显示
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    fetchDeptList()
    if (props.mode === 'edit' && props.deptData) {
      Object.assign(formData, props.deptData)
    } else {
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    deptName: '',
    parentId: 0,
    orderNum: 0,
    leader: '',
    phone: '',
    email: '',
    status: '0'
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return

  loading.value = true
  try {
    if (props.mode === 'add') {
      await saveDept(formData)
      ElMessage.success('新增成功')
    } else {
      await updateDept(formData)
      ElMessage.success('更新成功')
    }
    emit('success')
    visible.value = false
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchDeptList()
})
</script>
